<?php
/**
 * (actions) 采购计划-关闭采购计划
 */
namespace App\Admin\Actions\Purchase;

use App\Models\Stocking\StockingApply;
use App\Models\Stocking\StockingApplyDetail;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;
class PlanBatchClose extends BatchAction
{
    public $name = '关闭采购计划';

    public function handle(Collection $collection)
    {
        try{
            $count = 0;
            foreach ($collection as $model) {
                if($model->status != 1){ //已审核
                    continue;
                }
                //更新备货单明细状态
                $model->status = 2; //已关闭
                $flag1 = $model->save();

                //更新备货单状态
                $flag2 = $this->_upStatus($model->stocking_no);
                if($flag1 && $flag2){
                    $count++;
                }
            }
            return $this->response()->success("成功关闭{$count}条记录！")->refresh();
        }catch (\Exception $e){
            report($e);
            return $this->response()->error('系统异常！');
        }
    }

    public function dialog()
    {
        $this->confirm('确定关闭？');
    }

    /**
     * 更新备货单状态
     * @param $stockingNo
     * @return bool
     */
    private function _upStatus($stockingNo){
        $detailStatus = StockingApplyDetail::query()
            ->where('stocking_no',$stockingNo)
            ->pluck('status')
            ->toArray();
        $status = min($detailStatus) == 2 ? 2 : 1; //备货单状态
        $sa = StockingApply::query()->where('stocking_no',$stockingNo)->first();
        $sa->status = $status;
        return $sa->save();
    }
}
